package org.linlinjava.litemall.wx.service;

import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallBookBoxMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.wx.util.WxResponseCode.GOODS_UNSHELVE;

/**
 * @author Administrator
 */
@Service
public class WxBookBoxService {
    @Resource
    private LitemallBookBoxMapper bookBoxMapper;
    @Autowired
    private LitemallGoodsProductService goodsProductService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private LitemallBookBoxService bookBoxService;

    /**
     * 添加到书箱
     *
     * @param userId
     * @param goodProductId
     * @return
     */
    public Object addToBookBox(Integer userId, Integer goodProductId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallGoodsProduct goodsProduct = goodsProductService.findById(goodProductId);
        if (goodsProduct == null) {
            return ResponseUtil.fail(500, "该商品已下架");
        }
        if (goodsProduct.getNumber() < 1) {
            return ResponseUtil.fail(500, "该书库存不足");
        }
        Integer goodsId = goodsProduct.getGoodsId();
        LitemallGoods goods = goodsService.findById(goodsId);
        LitemallCategory category = categoryService.findById(goods.getCategoryId());
        if (!category.getCanBorrow()) {
            return ResponseUtil.fail(500, "类目 " + category.getName() + " 不能借阅");
        }
        LitemallBookBox bookBox = bookBoxService.findByUserIdAndGoodsProductId(userId, goodProductId);
        if (bookBox != null) {
            bookBox.setNumber(bookBox.getNumber() + 1);
            bookBox.setUpdateTime(LocalDateTime.now());
            bookBox.setBookDigit(goods.getBookDigit());
            bookBoxMapper.updateByPrimaryKeySelective(bookBox);
        } else {
            bookBox = new LitemallBookBox();
            bookBox.setUserId(userId);
            bookBox.setGoodsId(goodsId);
            bookBox.setGoodsProductId(goodProductId);
            bookBox.setName(goods.getName());
            bookBox.setAuthor(goods.getAuthor());
            bookBox.setNumber(1);
            bookBox.setOriginalPrice(goodsProduct.getPrice());
            bookBox.setPicUrl(goodsProduct.getUrl());
            bookBox.setAddTime(LocalDateTime.now());
            bookBox.setUpdateTime(LocalDateTime.now());
            bookBox.setBookDigit(goods.getBookDigit());
            bookBoxMapper.insert(bookBox);
        }
        return ResponseUtil.ok(bookBox);
    }

    /**
     * 移除书箱中某本书
     *
     * @param bookBoxId
     * @return
     */
    public void delete(Integer bookBoxId) {
        bookBoxMapper.deleteByPrimaryKey(bookBoxId);
    }

    /**
     * 多选删除
     *
     * @param bookBoxIds
     */
    public void batchDelete(Integer[] bookBoxIds) {
        LitemallBookBoxExample example = new LitemallBookBoxExample();
        example.or().andIdIn(Arrays.asList(bookBoxIds.clone()));
        bookBoxMapper.deleteByExample(example);
    }


    /**
     * 获取当前用户的书箱信息
     *
     * @param userId
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public List<LitemallBookBox> queryList(Integer userId, String sort, String order) {
        LitemallBookBoxExample bookBoxExample = new LitemallBookBoxExample();
        bookBoxExample.or().andUserIdEqualTo(userId).andNumberGreaterThan(0);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            bookBoxExample.setOrderByClause(sort + " " + order);
        }
        List<LitemallBookBox> bookBoxes = bookBoxMapper.selectByExample(bookBoxExample);
        for (LitemallBookBox bookBox : bookBoxes) {
            LitemallGoodsProduct goodsProduct = goodsProductService.findById(bookBox.getGoodsProductId());
            if (goodsProduct == null) {
                delete(bookBox.getId());
            }
        }
        List<LitemallBookBox> bookBoxes1 = bookBoxes.stream().filter(bookBox -> {
            LitemallGoodsProduct goodsProduct = goodsProductService.findById(bookBox.getGoodsProductId());
            return goodsProduct != null && goodsProduct.getNumber() > 0;
        }).collect(Collectors.toList());
        List<LitemallBookBox> bookBoxList = bookBoxes1.stream().peek(bookBox -> {
            LitemallGoodsProduct goodsProduct = goodsProductService.findById(bookBox.getGoodsProductId());
            if (goodsProduct.getNumber() < bookBox.getNumber()) {
                bookBox.setNumber(goodsProduct.getNumber());
                update(userId, bookBox);
            }
        }).collect(Collectors.toList());

        return bookBoxList;
    }


    /**
     * 更新书箱
     *
     * @param userId
     * @param bookBox
     * @return
     */
    public Object update(Integer userId, LitemallBookBox bookBox) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer id = bookBox.getId();
        Integer goodsId = bookBox.getGoodsId();
        Integer goodsProductId = bookBox.getGoodsProductId();
        Integer number = bookBox.getNumber();
        if (number == 0) {
            bookBoxMapper.deleteByPrimaryKey(id);
            return ResponseUtil.ok();
        }
        if (!ObjectUtils.allNotNull(id, goodsId, goodsProductId, number)) {
            return ResponseUtil.fail(400, "id,goodsId,goodsProductId,number 有没传的参数");
        }
        LitemallBookBox existBookBox = bookBoxService.findByIdAndUserId(id, userId);
        if (existBookBox == null) {
            return ResponseUtil.fail(400, "该书箱不存在");
        }
        // 判断goodsId和productId是否与当前box里的值一致
        if (!existBookBox.getGoodsId().equals(goodsId)) {
            return ResponseUtil.badArgumentValue();
        }
        if (!existBookBox.getGoodsProductId().equals(goodsProductId)) {
            return ResponseUtil.badArgumentValue();
        }
        //判断商品是否可加入书箱
        LitemallGoods goods = goodsService.findById(goodsId);
        if (goods == null || !goods.getIsOnSale()) {
            return ResponseUtil.fail(GOODS_UNSHELVE, "商品已下架");
        }
        //取得规格的信息,判断规格库存
        LitemallGoodsProduct product = goodsProductService.findById(goodsProductId);
        if (product == null || product.getNumber() < number) {
            return ResponseUtil.fail(GOODS_UNSHELVE, "库存不足");
        }
        existBookBox.setNumber(number);
        bookBoxMapper.updateByPrimaryKeySelective(existBookBox);
        return ResponseUtil.ok();
    }


}
